package tools.crawler.images;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import org.junit.Test;

import com.easywan.util.DBUtils;
import com.easywan.util.DateUtils;
import com.easywan.util.ImageUtils;
import com.easywan.util.StringsUtils;
import com.easywan.util.Utils;

public class ImagesDeal {
	@Test
	public void start() throws SQLException,  IOException{
		Connection conn = DBUtils.getConnection();
		String sql = "select * from cj_spots_bief";
		PreparedStatement pstmtSpots = conn.prepareStatement(sql);
		ResultSet rs = pstmtSpots.executeQuery();
		//<img src="http://c.cncnimg.cn/037/318/42bf_b.jpg">
		//<img src="http://c.cncnimg.cn/038/035/7fff_b.jpg">
		String regex = "<img src=\"(.+?)\"";
		String path = "/upload/images/";
		String now = DateUtils.dateToPath();
		while(rs.next()){
			Integer id = rs.getInt("id");
			String content = rs.getString("content");
			//System.out.println(content);
			List<String> imageUrls = StringsUtils.mathes(content, regex);
			//System.out.println(imageUrls);
			//break;
			if(!Utils.listIsEmpty(imageUrls)){
				for(String imageUrl : imageUrls){
					String imagePath = path+now+UUID.randomUUID().toString()+".jpg";
					if(ImageUtils.save(imageUrl,imagePath,600)){
						content = content.replace(imageUrl, imagePath);
						String sql2 = "update cj_spots_bief set content = ? where id = ?";
						PreparedStatement contentPstmt = DBUtils.getConnection().prepareStatement(sql2);
						contentPstmt.setString(1, content);
						contentPstmt.setInt(2, id);
						contentPstmt.executeUpdate();
						contentPstmt.close();
						String sql3 = "insert into images(name,source) values(?,?)";
						PreparedStatement imagePstmt = DBUtils.getConnection().prepareStatement(sql3);
						imagePstmt.setString(1, imagePath);
						imagePstmt.setString(2, imageUrl);
						imagePstmt.executeUpdate();
						imagePstmt.close();
					}
				}
			}
		}
		pstmtSpots.close();
	}
	@Test
	public void start2() throws SQLException{
		Connection conn = DBUtils.getConnection();
		String sql = "select * from cj_spots_bief";
		PreparedStatement pstmtSpots = conn.prepareStatement(sql);
		ResultSet rs = pstmtSpots.executeQuery();
		while(rs.next()){
			Integer id = rs.getInt("id");
			String content = rs.getString("content");
			String sql2 = "update cj_spots_bief set content = ? where id = ?";
			content =  content.replace("div", "p") ;
			PreparedStatement contentPstmt = DBUtils.getConnection().prepareStatement(sql2);
			contentPstmt.setString(1, content);
			contentPstmt.setInt(2, id);
			contentPstmt.executeUpdate();
			contentPstmt.close();
		}
		pstmtSpots.close();
	}
}
